package com.colin.juc.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Colin on 2020/4/5 13:32
 * email: colinzhaodong@gmail.com
 * desc: //1000个打印日期的任务,用线程池来执行,利用ThreadLocal分配自己的dateFormat对象
 *
 * @author zhaod
 */
public class ThreadLocalUsageSixth {
	public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
	public static void main(String[] args) throws InterruptedException {
		for (int i = 0; i < 1000; i++) {
			int finalI = i;
			threadPool.submit(() -> {
				String date = new ThreadLocalUsageSixth().date(finalI);
				System.out.println(date);
			});
		}
		threadPool.shutdown();
	}

	public String date(int seconds) {
		//参数的单位是毫秒，从1970.1.1 00:00:00 GMT计时
		Date date = new Date(1000 * seconds);
//		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat dateFormat = ThreadSafeFormatter.dateFormatThreadLocal.get();
		return dateFormat.format(date);
	}
}
class ThreadSafeFormatter{
	public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}